//
//  AdaptiveBackgroundView.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2025/5/12.
//

#import "AdaptiveBackgroundView.h"

@implementation AdaptiveBackgroundView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
        
        [self setupPopupView];
        [self setupGesture];
    }
    return self;
}

- (void)setupView {
    // 设置背景样式
    self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    self.layer.cornerRadius = 20.0;
    self.layer.masksToBounds = YES;
    
    
    UIImageView *img = [[UIImageView alloc] init];
    img.image = [UIImage imageNamed:@"count_img"];
    [self addSubview:img];
    
    // 创建 label
    _countLabel = [[UILabel alloc] init];
    _countLabel.textColor = [UIColor whiteColor];
    _countLabel.font = [UIFont systemFontOfSize:14];
    _countLabel.textAlignment = NSTextAlignmentCenter;
//    _countLabel.text = @"暂无在线观众";
    [self addSubview:_countLabel];
    
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(15,15));
        make.top.mas_equalTo(self).offset(5);
        make.centerX.mas_equalTo(self);
    }];
    
    // 使用 Masonry 布局
    [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self).insets(UIEdgeInsetsMake(5, 10, 5, 10));
        make.left.mas_equalTo(self).offset(20);
        make.right.mas_equalTo(self).offset(-20);
        make.bottom.mas_equalTo(self).offset(-5);
        make.top.mas_equalTo(img.mas_bottom).offset(0);
    }];
    
    // 初始值
    _currentCount = 0;
    _totalCount = 0;
    [self updateLabelText];
}

- (void)setupPopupView {
    // 创建弹出视图
    _popupView = [[UIView alloc] init];
    _popupView.backgroundColor = [UIColor darkGrayColor];
    _popupView.hidden = YES;
    // 设置圆角
    _popupView.layer.cornerRadius = 5;
    _popupView.layer.masksToBounds = YES;
    _popupView.alpha = 0; // 初始完全透明
    
    // 创建弹出视图中的label
    _popupLabel = [[UILabel alloc] init];
    _popupLabel.textColor = [UIColor whiteColor];
    _popupLabel.font = [UIFont systemFontOfSize:14];
    _popupLabel.numberOfLines = 0;
    _popupLabel.textAlignment = NSTextAlignmentLeft;
    [_popupView addSubview:_popupLabel];
    
    // 使用 Masonry 布局弹出视图中的label
    [_popupLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_popupView).insets(UIEdgeInsetsMake(10, 10, 10, 10));
    }];
}

- (void)setupGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:tap];
}

- (void)handleTap:(UITapGestureRecognizer *)gesture {
    if (!_popupView.superview) {
        // 获取keyWindow来添加popupView
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        [keyWindow addSubview:_popupView];
        
        // 转换frame到window坐标系
        CGRect convertedFrame = [self convertRect:self.bounds toView:keyWindow];
        
        // 更新popupView约束
        [_popupView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(keyWindow).offset(CGRectGetMaxY(convertedFrame) + 5);
            make.right.equalTo(keyWindow.mas_right).offset(-15);
            make.width.equalTo(@100);
//            make.height.equalTo(@40);
        }];
    }
    
    if (_popupView.hidden) {
        // 显示弹出视图（带动画）
        _popupView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.popupView.alpha = 1;
        }];
        
        // 更新弹出视图内容
        _popupLabel.text = [NSString stringWithFormat:@"在线人数:%ld \n最高在线:%ld", (long)_currentCount, (long)_totalCount];
        
        // 3秒后自动隐藏
        [self performSelector:@selector(hidePopup) withObject:nil afterDelay:3.0];
    } else {
        [self hidePopup];
    }
}

- (void)hidePopup {
    [UIView animateWithDuration:0.3 animations:^{
        self.popupView.alpha = 0;
    } completion:^(BOOL finished) {
        self.popupView.hidden = YES;
    }];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hidePopup) object:nil];
}

- (void)updateCount:(NSInteger)currentCount totalCount:(NSInteger)totalCount {
    _currentCount = currentCount;
    _totalCount = totalCount;
    [self updateLabelText];
    
    // 通知系统需要更新布局
    [self setNeedsUpdateConstraints];
    [self layoutIfNeeded];
}

- (void)updateLabelText {
    _countLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)_currentCount, (long)_totalCount];
}

- (void)dealloc {
    // 移除弹出视图
    [_popupView removeFromSuperview];
}
@end
